import { IRootState } from '@/store/types'
import { Module } from 'vuex'
import { IProductState } from './types'
import { getPageListData } from '@/serivce/main/system/system'
import { IDataType } from '@/serivce/types'

const pageUrlMap: { [key: string]: string } = {
  'goods': '/vue3goods/listp'
}

/**
 * 2021年10月5日 16:32:44 chanchaw
 * 拷贝自 src\store\main\system\system.ts
 */
const productModule: Module<IProductState, IRootState> = {
  namespaced: true,
  state() {
    return {
      goodsList: [],
      goodsCount: 0
    }
  },
  mutations: {
    changeGoodsList(state, goodsList: any[]) {
      state.goodsList = goodsList
    },
    changeGoodsCount(state, goodsCount: number) {
      state.goodsCount = goodsCount
    }
  },
  getters: {
    pageListData(state) {
      return (pageName: string) => {
        return (state as any)[`${pageName}List`]
      }
    },
    pageListCount(state) {
      return (pageName: string) => {
        return (state as any)[`${pageName}Count`]
      }
    }
  },
  actions: {
    async getPageListAction({ commit }, payload: any) {
      const pageName: string = payload.pageName
      const pageUrl = pageUrlMap[pageName]

      const pageResult: IDataType = await getPageListData(pageUrl, payload.queryInfo)
      const pageList = pageResult.data
      const pageCount = pageResult.data.length ?? 0
      const capitalFirst = pageName.replace(pageName[0], pageName[0].toUpperCase())
      const changeListMethodName = `change${capitalFirst}List`
      const changeCountMethodName = `change${capitalFirst}Count`
      commit(changeListMethodName, pageList)
      commit(changeCountMethodName, pageCount)
    }
  }
}

export default productModule
